<template>
	<div class="app-container">
    <div class="filter-container tw-filter">
      <el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-edit" v-has="$store.state.user.btn_common+'add'" @click="handleAdd()">添加</el-button>
      <el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-delete" v-has="$store.state.user.btn_common+'del'" @click="handleDelete()">批量删除</el-button>

      <el-input v-model="queryList.name" placeholder="请输入权限组名称" class="filter-item tw-filter-input" clearable/>
      <el-select v-model="queryList.state" class="filter-item tw-filter-input" placeholder="请选择状态" clearable>
        <el-option key="" label="全部状态" value="" />
        <el-option key="1"  label="启用" value="1" />
        <el-option key="0" label="禁用" value="0" />
      </el-select>

      <el-button v-waves class="filter-item tw-filter-button" size="medium" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="tableList"
      @selection-change="handleSelectionChange"
      border fit  highlight-current-row style="width: 100%;"
      >
      <el-table-column type="selection" width="50" />
      <el-table-column label="排序" prop="sort_id" align="center" width="80" v-has="$store.state.user.btn_common+'edit'">
        <template slot-scope="{row}">
          <el-input v-model="row.sort_id" class="edit-input" size="small" @change="updateSort(row.id, row.sort_id)" />
        </template>
      </el-table-column>
      <el-table-column label="权限组名称" prop="name" align="left"/>
      <el-table-column label="描述" prop="desc" align="left"/>
      <el-table-column label="添加时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.add_time | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
      	<template slot-scope="{row}">
      		<span v-if="row.state == 1">启用</span>
      		<span v-else>禁用</span>
      	</template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" v-has="$store.state.user.btn_common+'edit'" @click="handleEdit(row.id)">编辑</el-button>
          <el-button size="mini" v-has="$store.state.user.btn_common+'upshow'" v-if="row.state" @click="handleUpshow(row.id)">禁用</el-button>
          <el-button size="mini" v-has="$store.state.user.btn_common+'show'" v-else @click="handleShow(row.id)">启用</el-button>
          <el-button size="mini" v-has="$store.state.user.btn_common+'del'" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="isPage && listTotal > 0" :total="listTotal" :page.sync="queryList.curpage" :limit.sync="queryList.page" @pagination="getList" />

		<!-- 添加/编辑 -->
		<el-dialog width="40%" @close="resetForm('dataForm')" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
		  <div style="width: 100%;height: 60vh;overflow-y: auto;">
			   <el-form label-position="right" label-width="120px" ref="dataForm" :rules="rules" :model="form">
			   		<el-form-item label="权限组名称" prop="name">
			   			<el-input v-model="form.name" placeholder="请输入权限组名称" />
			   		</el-form-item>
			   		<el-form-item label="描述" prop="desc">
			   			<el-input v-model="form.desc" type="textarea" :rows="5" placeholder="请输入描述信息" />
			   		</el-form-item>
			   <el-form-item label="权限">
			     <div class="over">
			       <el-tree
			         ref="tree"
			         :check-strictly="checkStrictly"
			         :data="routesList"
			         :props="defaultProps"
			         show-checkbox
			         node-key="id"
			         class="permission-tree tree"
			         :default-checked-keys="defaultChecked"
			         :default-expand-all="true"
			         :render-content="renderContent"
			       />
			     </div>
			   </el-form-item>
			   		<el-form-item label="状态">
			   			<el-radio-group v-model="form.state">
			   				<el-radio :label="1">启用</el-radio>
			   				<el-radio :label="0">禁用</el-radio>
			   			</el-radio-group>
			   		</el-form-item>
			   		<el-form-item label="排序" prop="sort_id">
			   			<el-input v-model="form.sort_id" />
			   		</el-form-item>
			   	</el-form>
		   </div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogStatus==='create'?createData():updateData()">保存</el-button>
				<el-button @click="dialogFormVisible = false">取消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import Pagination from '@/components/Pagination' // 基于el分页的二次封装
	import waves from '@/directive/waves' // waves directive

	export default {
		components: { Pagination },
		directives: { waves },
		data() {
			return {
				// 数据列表
				listLoading: true,
				listTotal: 0,
				isPage: false,
				tableList: [],
				multipleSelection: [],//多选数据
				// 添加/编辑弹窗
				dialogFormVisible: false,
				dialogStatus: '',
				textMap: {
					update: '编辑',
					create: '添加'
				},
				//键字段
				keyName: 'id',
				apiPath: 'admin.groups',
				apiPath1: 'admin.router',

				// 搜索数据
				queryList: {
					page: this.$store.state.settings.page, // 每页显示数量
					curpage: 1, // 当前页码
					name: '', //名称
          state: null  // 状态
				},

        // 表单数据
        form: {
          id: '',
          name: '',  // 名称
          desc: '',  // 描述
          limits_check:'',
          limits_half:'',
          state: 1, // 状态，0禁用，1启用
          sort_id: 255  // 排序
        },
        // 重置数据
        formReset: {
          id: '',
          name: '',  // 名称
          desc: '',  // 描述
          limits_check:'',
          limits_half:'',
          state: 1, // 状态，0禁用，1启用
          sort_id: 255  // 排序
        },
        // 验证
        rules: {
          name: [{ required: true, message: '请输入权限组名称！', trigger: 'change' }]
        },

				//授权
				checkStrictly: false,
				defaultProps: {
					children: 'children',
					label: 'name'
				},
				routesList: [],
				defaultChecked: [],
			}
		},
		created() {
      //获取数据列表
			this.getList();
			//获取权限菜单
			this.getRoutes();
		},
		methods: {
      //获取权限菜单
      getRoutes() {
      	this.$api.fetchList({ state: 1}, this.apiPath1).then(response => {
      		this.routesList = response.list //数据列表
      	})
      },

      // 搜索
      handleFilter() {
      	this.queryList.curpage = 1
      	this.tableList = []
        this.listTotal = 0
      	this.getList()
      },
      // 列表选择
      handleSelectionChange(val) {
      	this.multipleSelection = val
      },
      // 重置form
      resetForm() {
      	this.form = JSON.parse(JSON.stringify(this.formReset))
      },
      // 获取数据列表
      getList() {
      	this.listLoading = true
      	this.$api.fetchList(this.queryList, this.apiPath).then(response => {
      		this.tableList = response.list
      		this.listTotal = response.list_count
      		this.isPage = response.is_page
          this.listLoading = false
      	})
      },
      // 添加
      handleAdd() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true

        //重置授权选择
        this.$refs.tree.setCheckedNodes([]);

        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      // 编辑
      handleEdit(id = 0) {
        this.resetForm()
      	this.checkStrictly = true;

        // 获取详情
        this.$api.getDetail({ id: id }, this.apiPath).then(response => {
          //数据处理
          for(let key in this.form){
            if(response.detail.hasOwnProperty(key)){
              this.form[key] = response.detail[key]
            }
          }
          //权限菜单处理
          this.$refs.tree.setCheckedNodes(response.detail.limits_check_arr)
          this.defaultChecked = response.detail.limits_check_arr;
          this.checkStrictly = false;
        })

        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
        })
      },
      // 添加-数据提交
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            //权限选择处理
            //选中
            let checkedKeys = this.$refs.tree.getCheckedKeys();
            if (checkedKeys.length > 0) {
            	this.form.limits_check = checkedKeys.toString();
            } else {
            	this.form.limits_check = '';
            }
            //半选中
            let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
            if (halfCheckedKeys.length > 0) {
            	this.form.limits_half = halfCheckedKeys.toString();
            } else {
            	this.form.limits_half = '';
            }

            this.$api.add(this.form, this.apiPath).then(() => {
              // 重新获取列表
              this.queryList.curpage = 1
              this.tableList = []
              this.getList()

              //重置授权选择
              this.$refs.tree.setCheckedNodes([]);
              this.dialogFormVisible = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 编辑-数据提交
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            //权限选择处理
            //选中
            let checkedKeys = this.$refs.tree.getCheckedKeys();
            if (checkedKeys.length > 0) {
            	this.form.limits_check = checkedKeys.toString();
            } else {
            	this.form.limits_check = '';
            }

            let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
            if (halfCheckedKeys.length > 0) {
            	this.form.limits_half = halfCheckedKeys.toString();
            } else {
            	this.form.limits_half = '';
            }

            this.$api.edit(this.form, this.apiPath).then(response => {
              // 重新获取列表
              this.getList()

      				//重置授权选择
      				this.$refs.tree.setCheckedNodes([]);
              this.dialogFormVisible = false
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 删除
      handleDelete(id = 0) {
        let current = this
        let id_str = ''
        if (!id) {
          // 多选
          if (!this.multipleSelection.length) {
            this.$message({
              message: '请选择删除的条目！',
              type: 'warning'
            })
            return false
          }
          // 数据处理
          this.multipleSelection.forEach(item => {
            id_str += item[current.keyName] + ','
          })
        } else {
          id_str = id
        }

        // 提交数据
        this.$confirm('确认删除数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.del({ id_str: id_str }, this.apiPath).then(response => {
            // 重新获取列表
            this.getList()
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          })
        })
      },
      // 排序
      updateSort(id = 0, sort = '') {
      	this.$api.editSort({
      		id: id,
      		sort: sort
      	}, this.apiPath).then(response => {
      		this.$message({
      			message: '排序成功',
      			type: 'success'
      		})
      	})
      },
      //启用
      handleShow(id = 0) {
      	this.$confirm('确认启用数据吗?', '提示', {
      		confirmButtonText: '确定',
      		cancelButtonText: '取消',
      		type: 'warning'
      	}).then(() => {
      		this.$api.show({ id_str: id }, this.apiPath).then(response => {
      			// 重新获取列表
      			this.getList()
      			this.$message({
      				message: '启用成功',
      				type: 'success'
      			})
      		})
      	})
      },
      //禁用
      handleUpshow(id = 0) {
      	this.$confirm('确认禁用数据吗?', '提示', {
      		confirmButtonText: '确定',
      		cancelButtonText: '取消',
      		type: 'warning'
      	}).then(() => {
      		this.$api.upshow({ id_str: id }, this.apiPath).then(response => {
      			// 重新获取列表
      			this.getList()
      			this.$message({
      				message: '禁用成功',
      				type: 'success'
      			})
      		})
      	})
      },

			// 内容区渲染后执行 判断底层 赋 class
			renderContent(h, {
				node,
				data,
				store
			}) {
				//树节点的内容区的渲染 Function
				let classname = "";
				// 由于项目中有三级菜单也有四级级菜单，就要在此做出判断
				if (node.level === 5) {
					classname = "foo";
				}
				if (node.level === 4 && node.childNodes.length === 0) {
					classname = "foo";
				}
				/* this.$nextTick(() => {
				  this.changeCss()
				 });*/
				return h(
					"p", {
						class: classname,
					},
					node.label
				);
			},
			changeCss() {
				var levelName = document.getElementsByClassName("foo"); // levelname是上面的最底层节点的名字
				for (var i = 0; i < levelName.length; i++) {
					// cssFloat 兼容 ie6-8  styleFloat 兼容ie9及标准浏览器
					levelName[i].parentNode.style.cssFloat = "left"; // 最底层的节点，包括多选框和名字都让他左浮动
					levelName[i].parentNode.style.styleFloat = "left";
					levelName[i].parentNode.onmouseover = function() {
						this.style.backgroundColor = "#fff";
					};
				}
			}

		}
	}
</script>
<style scoped>
	.over /deep/ .el-tree>.el-tree-node:after {
		border-top: none;
		
	}

	.over /deep/ .el-tree-node :last-child:before {
		height: 38px;
	}

	.over /deep/ .el-tree>.el-tree-node:before {
		border-left: none;
	}

	.over /deep/ .el-tree>.el-tree-node:after {
		border-top: none;
	}

	.over /deep/ .el-tree-node {
		position: relative;
		padding-left: 16px;
	}

	.over /deep/ .el-tree-node__children {
		padding-left: 16px;
	}

	.over /deep/ .el-tree-node:before {
		content: "";
		left: -4px;
		position: absolute;
		right: auto;
		border-width: 1px;
	}

	.over /deep/ .el-tree-node:after {
		content: "";
		left: -4px;
		position: absolute;
		right: auto;
		border-width: 1px;
	}

	.over /deep/ .el-tree-node:before {
		border-left: 1px solid #999;
		/* 指示线的样式和颜色粗细 */
		bottom: 0px;
		height: 100%;
		top: -26px;
		width: 1px;
	}

	.over /deep/ .el-tree-node:after {
		border-top: 1px solid #999;
		/* 指示线的样式和颜色粗细 */
		height: 20px;
		top: 12px;
		width: 24px;
	}
</style>
